// --- Start of ListComponent ---
const ListComponent = {
  template: `
    <div class="app-container">
      <div class="page-header">
        <h1 class="page-title">消息通知管理</h1>
      </div>

      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" ref="filterForm" size="small">
          <el-form-item label="标题">
            <el-input v-model="filterForm.title" placeholder="请输入标题关键字" clearable></el-input>
          </el-form-item>
          <el-form-item label="通知人群">
            <el-select v-model="filterForm.target_type" placeholder="请选择" clearable>
              <el-option label="所有用户" :value="1"></el-option>
              <el-option label="指定角色" :value="2"></el-option>
              <el-option label="指定用户" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="请选择" clearable>
              <el-option label="草稿" :value="1"></el-option>
              <el-option label="已发布" :value="2"></el-option>
              <el-option label="未生效" :value="3"></el-option>
              <el-option label="生效中" :value="4"></el-option>
              <el-option label="已过期" :value="5"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="优先级">
            <el-select v-model="filterForm.priority" placeholder="请选择" clearable>
              <el-option label="紧急" :value="1"></el-option>
              <el-option label="高" :value="2"></el-option>
              <el-option label="中" :value="3"></el-option>
              <el-option label="低" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生效时间">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                :clearable="true"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>

        <div style="margin-top: 20px;">
          <el-button type="primary" @click="handleAdd">新增消息</el-button>
        </div>
      </div>

      <div class="table-container">
        <el-table
            v-loading="loading"
            :data="messageList"
            border
            style="width: 100%">
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip></el-table-column>
          <el-table-column prop="target_type_text" label="通知人群" width="100"></el-table-column>
          <el-table-column label="通知类型" width="150">
            <template slot-scope="scope">
              <el-tag
                  v-for="type in scope.row.notification_type"
                  :key="type"
                  size="mini"
                  class="notification-type-tag"
              >
                {{ formatNotificationType(type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-tag
                  :class="'el-tag--' + getStatusClass(scope.row.status)"
                  size="mini"
              >{{ scope.row.status_text }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="优先级" width="80">
            <template slot-scope="scope">
              <el-tag
                  :class="'el-tag--' + getPriorityClass(scope.row.priority)"
                  size="mini"
              >{{ scope.row.priority_text }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="生效时间" width="280">
            <template slot-scope="scope">
              {{ formatTimestamp(scope.row.effective_start_at) }} 至 {{ formatTimestamp(scope.row.effective_end_at) }}
            </template>
          </el-table-column>
          <el-table-column label="发布时间" width="160">
            <template slot-scope="scope">
              {{ formatTimestamp(scope.row.published_at) }}
            </template>
          </el-table-column>
          <el-table-column label="阅读情况" width="120">
            <template slot-scope="scope">
              {{ scope.row.read_count }}/{{ scope.row.total_user_count }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button
                  v-if="scope.row.status === 1"
                  type="success"
                  size="mini"
                  class="operation-btn"
                  @click="handlePublish(scope.row.id)"
              >发布</el-button>
              <el-button
                  type="primary"
                  size="mini"
                  class="operation-btn"
                  @click="handleEdit(scope.row.id)"
              >编辑</el-button>
              <el-button
                  type="danger"
                  size="mini"
                  class="operation-btn"
                  @click="handleDelete(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.page"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pagination.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total">
          </el-pagination>
        </div>
      </div>
    </div>
  `,
  data() {
    return {
      loading: false,
      messageList: [],
      dateRange: null,
      filterForm: {
        title: '',
        target_type: null,
        status: null,
        priority: null,
        start_time: null,
        end_time: null
      },
      pagination: {
        page: 1,
        page_size: 10,
        total: 0
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.loading = true;
      const baseUrl = '/api/admin/messages'; // Adjust if your API is hosted elsewhere

      const params = {
        page: this.pagination.page,
        page_size: this.pagination.page_size,
        ...this.filterForm
      };

      const queryString = Object.keys(params)
      .filter(key => params[key] !== null && params[key] !== undefined && params[key] !== '')
      .map(key => `${ encodeURIComponent(key) }=${ encodeURIComponent(params[key]) }`)
      .join('&');

      window.we.fetch(`${ baseUrl }?${ queryString }`)
      .then(data => {
        if(data.code === 0 && data.data) {
          this.messageList = data.data.list.map(item => ({
            ...item,
            target_type_text: this.formatTargetType(item.target_type),
            status_text: this.formatStatus(item.status),
            priority_text: this.formatPriority(item.priority)
          }));
          this.pagination.total = data.data.total;
        } else {
          this.$message.error(data.message || '获取消息列表失败');
        }
      })
      .catch(error => {
        console.error('获取消息列表出错:', error);
        this.$message.error('获取消息列表出错: ' + error.message);
      })
      .finally(() => {
        this.loading = false;
      });
    },

    handleSearch() {
      if(this.dateRange && this.dateRange.length === 2) {
        this.filterForm.start_time = this.dateRange[0];
        this.filterForm.end_time = this.dateRange[1];
      } else {
        this.filterForm.start_time = null;
        this.filterForm.end_time = null;
      }
      this.pagination.page = 1;
      this.fetchData();
    },

    handleReset() {
      this.filterForm = {
        title: '',
        target_type: null,
        status: null,
        priority: null,
        start_time: null,
        end_time: null
      };
      this.dateRange = null;
      this.pagination.page = 1;
      this.fetchData();
    },

    handleSizeChange(val) {
      this.pagination.page_size = val;
      this.fetchData();
    },

    handleCurrentChange(val) {
      this.pagination.page = val;
      this.fetchData();
    },

    handleAdd() {
      this.$router.push('/edit');
    },

    handleEdit(id) {
      this.$router.push(`/edit/${ id }`);
    },

    handleDelete(id) {
      this.$confirm('确认删除该消息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = `/api/admin/messages/${ id }`; // Adjust if your API is hosted elsewhere
        fetch(url, { method: 'DELETE' })
        .then(data => {
          if(data.code === 0) {
            this.$message({ type: 'success', message: '删除成功!' });
            this.fetchData(); // Refresh list
          } else {
            this.$message.error(data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除消息出错:', error);
          this.$message.error('删除消息出错: ' + error.message);
        });
      }).catch(() => { /* User cancelled */ });
    },

    handlePublish(id) {
      this.$confirm('确认发布该消息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const url = `/api/admin/messages/${ id }/publish`; // Adjust if your API is hosted elsewhere
        window.we.fetch(url, { method: 'POST' }) // Assuming POST for publish action
        .then(data => {
          if(data.code === 0) {
            this.$message({ type: 'success', message: '发布成功!' });
            this.fetchData(); // Refresh list
          } else {
            this.$message.error(data.message || '发布失败');
          }
        })
        .catch(error => {
          console.error('发布消息出错:', error);
          this.$message.error('发布消息出错: ' + error.message);
        });
      }).catch(() => { /* User cancelled */ });
    },

    formatTimestamp(timestamp) {
      if(!timestamp) return '--';
      const date = new Date(timestamp);
      // Simplified toISOString and substring for YYYY-MM-DD HH:MM
      try {
        return date.toLocaleString('zh-CN', {
          year: 'numeric', month: '2-digit', day: '2-digit',
          hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
        }).replace(/\//g, '-');
      } catch (e) {
        return new Date(timestamp).toISOString().slice(0, 16).replace('T', ' ');
      }
    },
    formatTargetType(type) {
      const map = { 1: '所有用户', 2: '指定角色', 3: '指定用户' };
      return map[type] || '未知';
    },
    formatStatus(status) {
      const map = { 1: '草稿', 2: '已发布', 3: '未生效', 4: '生效中', 5: '已过期' };
      return map[status] || '未知';
    },
    formatPriority(priority) {
      const map = { 1: '紧急', 2: '高', 3: '中', 4: '低' };
      return map[priority] || '未知';
    },
    formatNotificationType(type) {
      const typeMap = { 'app_popup': 'App弹框', 'app_push': 'App推送' };
      return typeMap[type] || type;
    },
    getStatusClass(status) {
      const statusMap = { 1: 'draft', 2: 'published', 3: 'inactive', 4: 'published', 5: 'expired' };
      return statusMap[status] || 'draft';
    },
    getPriorityClass(priority) {
      const priorityMap = { 1: 'urgent', 2: 'high', 3: 'medium', 4: 'low' };
      return priorityMap[priority] || 'medium';
    }
  }
};
// --- End of ListComponent ---

// --- Start of EditComponent ---
const EditComponent = {
  template: `
    <div class="app-container">
      <div class="page-header">
        <h1 class="page-title">{{ isEdit ? '编辑消息' : '新增消息' }}</h1>
        <el-button size="small" @click="goBack">返回列表</el-button>
      </div>

      <div class="form-container">
        <el-form :model="messageForm" :rules="rules" ref="messageForm" label-width="120px" size="small">
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="form-section-title">基本信息</h3>

            <el-form-item label="通知人群" prop="target_type" class="required-field">
              <el-radio-group v-model="messageForm.target_type" @change="handleTargetTypeChange">
                <el-radio :label="1">所有用户</el-radio>
                <el-radio :label="2">指定角色</el-radio>
                <el-radio :label="3">指定用户</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
                v-if="messageForm.target_type === 2"
                label="选择角色"
                prop="role_ids"
                class="required-field"
            >
              <el-select
                  v-model="messageForm.role_ids"
                  multiple
                  placeholder="请选择角色"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in roleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
                v-if="messageForm.target_type === 3"
                label="选择用户"
                prop="user_ids"
                class="required-field"
            >
              <el-select
                  v-model="messageForm.user_ids"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入用户名搜索"
                  :remote-method="remoteSearchUsers"
                  :loading="userLoading"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in userOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="通知类型" prop="notification_type" class="required-field">
              <el-checkbox-group v-model="messageForm.notification_type">
                <el-checkbox label="app_popup">App弹框</el-checkbox>
                <el-checkbox label="app_push" disabled>App推送</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="优先级" prop="priority" class="required-field">
              <el-select v-model="messageForm.priority" placeholder="请选择优先级">
                <el-option label="紧急" :value="1"></el-option>
                <el-option label="高" :value="2"></el-option>
                <el-option label="中" :value="3"></el-option>
                <el-option label="低" :value="4"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="生效时间" prop="effective_time" class="required-field">
              <el-date-picker
                  v-model="messageForm.effective_time"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期时间"
                  end-placeholder="结束日期时间"
                  value-format="timestamp"
                  :default-time="['00:00:00', '23:59:59']"
                  style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </div>

          <!-- 内容设置 -->
          <div class="form-section">
            <h3 class="form-section-title">内容设置</h3>
            <div class="language-tabs">
              <el-tabs v-model="activeLanguage" type="card">
                <el-tab-pane label="中文" name="zh"></el-tab-pane>
                <el-tab-pane label="English" name="en"></el-tab-pane>
                <el-tab-pane label="ភាសាខ្មែរ" name="km"></el-tab-pane>
                <el-tab-pane label="Filipino" name="fil"></el-tab-pane>
              </el-tabs>
            </div>

            <el-form-item :label="'标题 (' + activeLanguageLabel + ')'" :prop="'contents.' + activeLanguage + '.title'" class="required-field" :rules="rules['contents.'+activeLanguage+'.title']">
              <el-input
                  v-model="messageForm.contents[activeLanguage].title"
                  placeholder="请输入标题"
                  maxlength="50"
                  show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item :label="'简短内容 (' + activeLanguageLabel + ')'" :prop="'contents.' + activeLanguage + '.content'" class="required-field" :rules="rules['contents.'+activeLanguage+'.content']">
              <el-input
                  v-model="messageForm.contents[activeLanguage].content"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入简短内容"
                  maxlength="200"
                  show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item :label="'正文内容 (' + activeLanguageLabel + ')'" :prop="'contents.' + activeLanguage + '.body'">
              <div class="quill-editor" :id="'editor-' + activeLanguage"></div>
            </el-form-item>
          </div>

          <!-- 发布设置 -->
          <div class="form-section">
            <h3 class="form-section-title">发布设置</h3>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="messageForm.status">
                <el-radio :label="1">保存为草稿</el-radio>
                <el-radio :label="2">立即发布</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="form-actions">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitLoading">{{ isEdit ? '保存' : '提交' }}</el-button>
          </div>
        </el-form>
      </div>
    </div>
  `,
  data() {
    const defaultContentRules = (langName) => [
      { required: true, message: `请输入${langName}标题`, trigger: 'blur' }
    ];
    const defaultShortContentRules = (langName) => [
      { required: true, message: `请输入${langName}简短内容`, trigger: 'blur' }
    ];

    return {
      isEdit: false,
      messageId: null,
      submitLoading: false,
      activeLanguage: 'zh',
      editors: {}, // To store Quill instances
      messageForm: this.getInitialMessageForm(),
      rules: {
        target_type: [{ required: true, message: '请选择通知人群', trigger: 'change' }],
        role_ids: [{ validator: (rule, value, callback) => {
            if (this.messageForm.target_type === 2 && (!this.messageForm.role_ids || this.messageForm.role_ids.length === 0)) {
              callback(new Error('请选择角色'));
            } else { callback(); }
          }, trigger: 'change' }],
        user_ids: [{ validator: (rule, value, callback) => {
            if (this.messageForm.target_type === 3 && (!this.messageForm.user_ids || this.messageForm.user_ids.length === 0)) {
              callback(new Error('请选择用户'));
            } else { callback(); }
          }, trigger: 'change' }],
        notification_type: [{ validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              callback(new Error('请选择至少一种通知类型'));
            } else { callback(); }
          }, trigger: 'change' }],
        priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
        effective_time: [{ validator: (rule, value, callback) => {
            if (!value || value.length !== 2) {
              callback(new Error('请选择生效时间范围'));
            } else { callback(); }
          }, trigger: 'change' }],
        'contents.zh.title': defaultContentRules('中文'),
        'contents.zh.content': defaultShortContentRules('中文'),
        'contents.en.title': defaultContentRules('英文'),
        'contents.en.content': defaultShortContentRules('英文'),
        'contents.km.title': defaultContentRules('柬埔寨语'),
        'contents.km.content': defaultShortContentRules('柬埔寨语'),
        'contents.fil.title': defaultContentRules('菲律宾语'),
        'contents.fil.content': defaultShortContentRules('菲律宾语'),
      },
      roleOptions: [
        { value: 1, label: '管理员' }, { value: 2, label: '运营' },
        { value: 3, label: '客服' }, { value: 4, label: '普通用户' }
      ],
      userOptions: [],
      userLoading: false,
      languageMap: { zh: '中文', en: 'English', km: 'ភាសាខ្មែរ', fil: 'Filipino' }
    };
  },
  computed: {
    activeLanguageLabel() {
      return this.languageMap[this.activeLanguage] || this.activeLanguage;
    }
  },
  created() {
    this.messageId = this.$route.params.id;
    this.isEdit = !!this.messageId;
    if (this.isEdit) {
      this.fetchMessageDetail();
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initQuillEditors();
    });
  },
  beforeDestroy() {
    Object.values(this.editors).forEach(editor => {
      if (editor && editor.container) {
        // More robust cleanup might be needed if Quill doesn't self-clean well
        const toolbar = editor.getModule('toolbar');
        if (toolbar && toolbar.container && toolbar.container.parentNode) {
          toolbar.container.parentNode.removeChild(toolbar.container);
        }
        // editor.container.innerHTML = ''; // Or some Quill specific destroy method
      }
    });
    this.editors = {};
  },
  watch: {
    activeLanguage(newVal, oldVal) {
      if (oldVal && this.editors[oldVal] && this.editors[oldVal].root) {
        this.messageForm.contents[oldVal].body = this.editors[oldVal].root.innerHTML;
      }
      this.$nextTick(() => {
        if (this.editors[newVal] && this.editors[newVal].root) {
          this.editors[newVal].root.innerHTML = this.messageForm.contents[newVal].body || '';
        } else if (this.editors[newVal] === undefined) { // Editor might not be initialized yet for this tab
          this.initQuillEditorForLanguage(newVal); // Initialize if not present
          if(this.editors[newVal] && this.editors[newVal].root) {
            this.editors[newVal].root.innerHTML = this.messageForm.contents[newVal].body || '';
          }
        }
      });
    },
    '$route'(to, from) { // Watch for route changes to re-initialize if navigating between edit pages
      if (to.path.startsWith('/edit/') && to.params.id !== from.params.id) {
        this.resetFormAndFetch();
      } else if (to.path === '/edit' && from.path.startsWith('/edit/')) { // From edit to new
        this.resetFormAndFetch();
      }
    }
  },
  methods: {
    resetFormAndFetch() {
      // Clear old editor instances more thoroughly
      Object.values(this.editors).forEach(editor => {
        if (editor && editor.container && editor.container.parentNode) {
          // editor.container.parentNode.removeChild(editor.container); // This can be problematic if Quill manages DOM elsewhere
        }
      });
      this.editors = {}; // Reset editors
      this.messageForm = this.getInitialMessageForm(); // Reset form data
      this.$refs.messageForm.resetFields(); // Reset el-form validation states

      this.messageId = this.$route.params.id;
      this.isEdit = !!this.messageId;

      this.$nextTick(() => {
        this.initQuillEditors(); // Re-initialize all editors
        if (this.isEdit) {
          this.fetchMessageDetail();
        } else {
          // For new form, ensure active language editor content is set (empty)
          if(this.editors[this.activeLanguage] && this.editors[this.activeLanguage].root) {
            this.editors[this.activeLanguage].root.innerHTML = '';
          }
        }
      });
    },
    getInitialMessageForm() {
      return {
        target_type: 1,
        role_ids: [],
        user_ids: [],
        notification_type: ['app_popup'],
        priority: 3,
        effective_time: [],
        status: 1,
        contents: {
          zh: { title: '', content: '', body: '' },
          en: { title: '', content: '', body: '' },
          km: { title: '', content: '', body: '' },
          fil: { title: '', content: '', body: '' }
        }
      };
    },
    initQuillEditorForLanguage(lang) {
      const editorContainer = document.getElementById(`editor-${lang}`);
      if (editorContainer && !this.editors[lang]) { // Initialize only if not already present
        const toolbarOptions = [
          ['bold', 'italic', 'underline', 'strike'], ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }], [{ 'list': 'ordered'}, { 'list': 'bullet' }],
          [{ 'script': 'sub'}, { 'script': 'super' }], [{ 'indent': '-1'}, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }], [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }], [{ 'font': [] }],
          [{ 'align': [] }], ['clean'], ['link', 'image']
        ];
        this.editors[lang] = new Quill(editorContainer, {
          modules: { toolbar: toolbarOptions },
          theme: 'snow'
        });
      }
    },
    initQuillEditors() {
      const languages = ['zh', 'en', 'km', 'fil'];
      languages.forEach(lang => {
        this.initQuillEditorForLanguage(lang);
        // Set initial content if available (e.g., after fetching data)
        if (this.editors[lang] && this.messageForm.contents[lang] && this.messageForm.contents[lang].body) {
          this.editors[lang].root.innerHTML = this.messageForm.contents[lang].body;
        } else if (this.editors[lang]) {
          this.editors[lang].root.innerHTML = ''; // Ensure it's empty if no body
        }
      });
    },
    fetchMessageDetail() {
      if (!this.messageId) return;
      this.submitLoading = true;
      window.we.fetch(`/api/admin/messages/${this.messageId}`) // Adjust API path if needed
      .then(resData => {
        if (resData.code === 0 && resData.data) {
          this.setFormData(resData.data);
        } else {
          this.$message.error(resData.message || '获取消息详情失败');
          this.goBack(); // Go back if fetching detail fails
        }
      })
      .catch(error => {
        console.error('获取消息详情出错:', error);
        this.$message.error('获取消息详情出错: ' + error.message);
        this.goBack(); // Go back on error
      })
      .finally(() => {
        this.submitLoading = false;
      });
    },
    setFormData(data) {
      this.messageForm.target_type = data.target_type;
      this.messageForm.role_ids = data.role_ids || [];
      this.messageForm.user_ids = data.user_ids || [];
      // Ensure user_ids are actual IDs if API returns objects
      if (data.user_ids && data.user_ids.length > 0 && typeof data.user_ids[0] === 'object') {
        this.messageForm.user_ids = data.user_ids.map(u => u.id || u.value);
        this.userOptions = data.user_ids.map(u => ({value: u.id || u.value, label: u.username || u.label}));
      } else {
        this.messageForm.user_ids = data.user_ids || [];
        if (this.messageForm.user_ids.length > 0 && this.userOptions.length === 0) {
          // If user_ids are present but options are not, you might need a way to fetch their labels
          // For now, this assumes API might provide full user objects or just IDs.
          // If only IDs, the select might show IDs until user searches.
        }
      }

      this.messageForm.notification_type = data.notification_type || ['app_popup'];
      this.messageForm.priority = data.priority;
      this.messageForm.effective_time = data.effective_start_at && data.effective_end_at ?
        [new Date(data.effective_start_at).getTime(), new Date(data.effective_end_at).getTime()] : []; // Ensure timestamp format for date picker
      this.messageForm.status = data.status;

      const languages = ['zh', 'en', 'km', 'fil'];
      languages.forEach(lang => {
        const contentData = data.contents.find(item => item.language === lang) || { title: '', content: '', body: '' };
        this.messageForm.contents[lang] = {
          title: contentData.title || '',
          content: contentData.content || '',
          body: contentData.body || ''
        };
      });

      this.$nextTick(() => {
        // Re-initialize or update Quill editors with fetched data
        languages.forEach(lang => {
          if (this.editors[lang] && this.editors[lang].root) {
            this.editors[lang].root.innerHTML = this.messageForm.contents[lang].body || '';
          } else {
            this.initQuillEditorForLanguage(lang); // Ensure it's initialized
            if(this.editors[lang] && this.editors[lang].root) {
              this.editors[lang].root.innerHTML = this.messageForm.contents[lang].body || '';
            }
          }
        });
        // Ensure form validation state is updated after data load
        this.$refs.messageForm.clearValidate();
      });
    },
    handleTargetTypeChange() {
      this.messageForm.role_ids = [];
      this.messageForm.user_ids = [];
      this.userOptions = []; // Clear previous user options
      // Trigger validation only for the relevant fields after a tick to ensure DOM update
      this.$nextTick(() => {
        if (this.messageForm.target_type === 2) this.$refs.messageForm.validateField('role_ids');
        if (this.messageForm.target_type === 3) this.$refs.messageForm.validateField('user_ids');
      });
    },
    remoteSearchUsers(query) {
      if (query.trim() === '') {
        this.userOptions = [];
        return;
      }
      this.userLoading = true;
      window.we.fetch(`/api/admin/users?keyword=${encodeURIComponent(query)}`) // Adjust API path if needed
      .then(resData => {
        if (resData.code === 0 && resData.data) {
          // Filter out already selected users from new options if necessary
          const selectedIds = new Set(this.messageForm.user_ids);
          this.userOptions = resData.data
          .map(item => ({ value: item.id, label: item.username }))
          .filter(item => !selectedIds.has(item.value)); // Example: don't show already selected as new options

          // Or, more simply, just show all results and let El-Select handle display of selected
          // this.userOptions = resData.data.map(item => ({ value: item.id, label: item.username }));
        } else {
          this.userOptions = [];
        }
      })
      .catch(error => {
        console.error('搜索用户出错:', error);
        this.userOptions = [];
      })
      .finally(() => {
        this.userLoading = false;
      });
    },
    submitForm() {
      // Save current active language's Quill content before validation
      if (this.editors[this.activeLanguage] && this.editors[this.activeLanguage].root) {
        this.messageForm.contents[this.activeLanguage].body = this.editors[this.activeLanguage].root.innerHTML;
      }

      this.$refs.messageForm.validate(valid => {
        if (!valid) {
          this.$message.error('请完善表单信息');
          // Find first invalid tab and switch to it
          const fields = this.$refs.messageForm.fields;
          for (const field of fields) {
            if (field.validateState === 'error') {
              const prop = field.prop;
              if (prop && prop.startsWith('contents.')) {
                const lang = prop.split('.')[1];
                if (lang && this.activeLanguage !== lang && this.languageMap[lang]) {
                  this.activeLanguage = lang;
                  this.$message.info(`已切换到 ${this.languageMap[lang]} 标签页，请检查错误。`);
                  break;
                }
              }
            }
          }
          return;
        }

        this.submitLoading = true;
        let title = undefined
        const contentsArray = Object.keys(this.messageForm.contents).map(lang => {
          if(!title){
            title = this.messageForm.contents[lang].title
          }
          return  {
          language: lang,
          title: this.messageForm.contents[lang].title,
          content: this.messageForm.contents[lang].content,
          body: (this.editors[lang] && this.editors[lang].root) ? this.editors[lang].root.innerHTML : this.messageForm.contents[lang].body
        }});

        const payload = {
          title,
          target_type: this.messageForm.target_type,
          role_ids: this.messageForm.target_type === 2 ? this.messageForm.role_ids : [],
          user_ids: this.messageForm.target_type === 3 ? this.messageForm.user_ids : [],
          notification_type: this.messageForm.notification_type,
          priority: this.messageForm.priority,
          effective_start_at: this.messageForm.effective_time[0],
          effective_end_at: this.messageForm.effective_time[1],
          status: this.messageForm.status,
          contents: contentsArray
        };

        let apiUrl = '/api/admin/messages'; // Adjust API path if needed
        let method = 'POST';

        if (this.isEdit && this.messageId) {
          apiUrl += `/${this.messageId}`;
          method = 'PUT';
        }

        window.we.fetch(apiUrl, {
          method,
          body: JSON.stringify(payload)
        })
        .then(data => {
          if (data.code === 0) {
            this.$message({ type: 'success', message: (this.isEdit && this.messageId) ? '修改成功' : '创建成功' });
            if (this.messageForm.status === 2 || !(this.isEdit && this.messageId)) { // If published or newly created
              this.goBack();
            } else if (this.isEdit && this.messageId && data.data && data.data.id) {
              // Stay on page for draft edit
            }
            // If it's a new item saved as draft, and API returns ID, update route
            if (!(this.isEdit && this.messageId) && data.data && data.data.id) {
              this.$router.replace({ path: `/edit/${data.data.id}` }); // Update URL without full reload
              this.messageId = data.data.id; // Update component state
              this.isEdit = true;
            }
          } else {
            this.$message.error(data.message || '操作失败');
          }
        })
        .catch(error => {
          console.error('提交表单出错:', error);
          this.$message.error('提交表单出错: ' + error.message);
        })
        .finally(() => {
          this.submitLoading = false;
        });
      });
    },
    goBack() {
      this.$router.push('/');
    }
  }
};
// --- End of EditComponent ---

// --- Vue Router Setup ---
const routes = [
  { path: '/', component: ListComponent, name: 'ListMessages' },
  { path: '/list', redirect: '/' }, // Alias for list
  { path: '/edit', component: EditComponent, name: 'AddMessage' },
  { path: '/edit/:id', component: EditComponent, name: 'EditMessage', props: true } // props: true passes route params as props
];

const router = new VueRouter({
  // mode: 'history', // Optional: for cleaner URLs, requires server config
  routes
});

// --- Main Vue Instance ---
new Vue({
  el: '#app',
  router,
});
